package com.ifacebox.face.track.ui;

import com.ifacebox.face.track.utils.ThreadUtils;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.Objects;

/**
 * @author znn
 */
public class FaceUserToolBar extends JToolBar implements ActionListener {
    private static final ImageIcon ADD_USER_ICON = new ImageIcon(Objects.requireNonNull(FaceUserToolBar.class.getResource("/save.png")));
    private static final ImageIcon DEL_USER_ICON = new ImageIcon(Objects.requireNonNull(FaceUserToolBar.class.getResource("/cancel.png")));
    private final JButton addFaceUser, delFaceUser;
    private final JFileChooser fileChooser;
    private final FaceUserDialog faceUserDialog;

    public FaceUserToolBar(FaceUserDialog faceUserDialog) {
        super.setFloatable(false);
        super.setLayout(new FlowLayout(FlowLayout.LEFT));
        super.add(this.addFaceUser = new JButton(ADD_USER_ICON) {{
            this.addActionListener(FaceUserToolBar.this);
        }});
        super.add(this.delFaceUser = new JButton(DEL_USER_ICON) {{
            this.addActionListener(FaceUserToolBar.this);
        }});
        this.faceUserDialog = faceUserDialog;
        this.fileChooser = new JFileChooser();
        this.fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        this.fileChooser.setFileFilter(new FileNameExtensionFilter("图片", "jpg", "png"));
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == this.addFaceUser) {
            if (JFileChooser.APPROVE_OPTION == this.fileChooser.showOpenDialog(this)) {
                this.addFaceUser.setEnabled(false);
                this.delFaceUser.setEnabled(false);
                ThreadUtils.runThread(() -> {
                    try {
                        if (this.fileChooser.getSelectedFile().isDirectory()) {
                            for (File file : Objects.requireNonNull(this.fileChooser.getSelectedFile().listFiles())) {
                                if (file.isFile()) {
                                    this.faceUserDialog.addFaceUser(file);
                                }
                            }
                        } else {
                            this.faceUserDialog.addFaceUser(this.fileChooser.getSelectedFile());
                        }
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(this, ex.toString(), ex.getMessage(), JOptionPane.ERROR_MESSAGE);
                    } finally {
                        this.addFaceUser.setEnabled(true);
                        this.delFaceUser.setEnabled(true);
                    }
                });
            }
        }
        if (e.getSource() == this.delFaceUser) {
            this.faceUserDialog.delFaceUser();
        }
    }
}
